package com.acme.exchange.service;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Random;

import com.acme.exchange.gui.userDataEnter;
import com.acme.exchange.network.MessageTransceiver;
import com.acme.exchange.network.client.Client;
import com.acme.exchange.network.client.ClientOrderWriter;
import com.acme.exchange.network.proto.MessageConstructor;
import com.acme.exchange.network.proto.Protocol.ExchangeMessage;
import com.acme.exchange.network.proto.Protocol.ExchangeMessage.OrderType;
import com.acme.exchange.network.proto.Protocol.ExchangeMessage.Side;

public class ClientRobot implements Runnable {

	private static final int NUMBER_OF_CLIENTS = 100;
	private volatile String username;
	private volatile ExchangeMessage newOrder;
	private volatile ExchangeMessage newOrder2;
	private volatile MessageTransceiver mt;
	private volatile SelectionKey key;

	public static void main(String[] args) {

		// System.out.printf("starting %d robots%n%n", NUMBER_OF_CLIENTS);

		for (int i = 0; i < NUMBER_OF_CLIENTS; i++) {
			(new Thread(new ClientRobot(i))).start();
		}
	}

	ClientRobot(int number) {
		username = String.format("robot_%d", number);
		mt = new MessageTransceiver();
	}

	@Override
	public void run() {

		Client client = new Client();
		// ClientOrderWriter cow = new ClientOrderWriter(client.getKey());
		// new Thread(cow).start();
		// client.run();
		key = client.getKey();
		try {
			newOrder = MessageConstructor.constructLoginMessage(username);
			synchronized ((SocketChannel) key.channel()) {
				mt.transmit(newOrder.toByteArray(),
						(SocketChannel) key.channel());
			}

			int clOrderId = 0;
			for (int i = 0; i < 100000; i++) {
				newOrder = MessageConstructor.constructNewOrder(clOrderId,
						OrderType.LIMIT, Side.BUY, "JAVA", 100, "10.0");
				synchronized ((SocketChannel) key.channel()) {
					mt.transmit(newOrder.toByteArray(),
							(SocketChannel) key.channel());
				}
				//Thread.sleep(10000);
				clOrderId++;
			}
			
			while (true) {
				newOrder = MessageConstructor.constructNewOrder(clOrderId,
						OrderType.LIMIT, Side.BUY, "JAVA", 100, "10.0");
				newOrder2 = MessageConstructor.constructNewOrder(clOrderId,
						OrderType.LIMIT, Side.SELL, "JAVA", 100, "10.0");
				synchronized ((SocketChannel) key.channel()) {
					mt.transmit(newOrder.toByteArray(),
							(SocketChannel) key.channel());
					mt.transmit(newOrder2.toByteArray(),
							(SocketChannel) key.channel());
				}
				Thread.sleep(5000);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
